﻿using Grpc.Net.Client.Balancer;
using Microsoft.Extensions.Options;
using Nacos.AspNetCore.V2;
using Nacos.V2;
using Nacos.V2.Common;
using Nacos.V2.Naming;
using Nacos.V2.Naming.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nacos.Provider.gRPC
{
    public class NacosResolverFactory : ResolverFactory
    {
        public override string Name => "nacos";

        private readonly INacosNamingService client;
        private readonly NacosGrpcChannelOptions grpcChannelOptions = null;

        public NacosResolverFactory(INacosNamingService client, IOptions<NacosGrpcChannelOptions> nacosGrpcChannelOptions)
            : base()
        {
            this.client = client;
            this.grpcChannelOptions = nacosGrpcChannelOptions.Value;
        }

        public override Resolver Create(ResolverOptions options)
        {
            string urlAddress = options.Address.ToString();
            var serviceName = urlAddress.Substring(urlAddress.LastIndexOf("/") + 1);
            var groupName = urlAddress.Substring(8, urlAddress.LastIndexOf("/") - 8);
            //请求nacos
            var instances = this.client.GetAllInstances(serviceName, groupName.ToUpper(), false).Result;
            return new NacosResolver(options.LoggerFactory, instances, this.grpcChannelOptions);
        }
    }
}
